/***************************************************
File:           LPK_RotateTowardsGameObject.cs
Authors:        Christopher Onorati
Last Updated:   5/20/2019
Last Version:   2018.3.14

Description:
  This component can be added to any object to cause it to 
  rotate itself to face the position of a specified object 
  either every frame or just once.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_RotateTowardsGameObject
* DESCRIPTION : Component used to cause a game object to always face another game object.
**/
public class LPK_RotateTowardsGameObject : LPK_Component
{
    /************************************************************************************/

    public bool m_bOnUpdate = true;

    [Tooltip("Initial object to rotate towards.  If deleted or set to null, this script will try to find a tagged object to face.")]
    [Rename("Initial Transform Object")]
    public GameObject m_pTargetTransformObject;

    [Tooltip("Tag to search for to find an object to face.")]
    [TagDropdown]
    public string m_TargetFacingTag;

    public float m_flRotationSpeed = 360.0f;

    /************************************************************************************/

    //Internal variable to handle single reorientation
    bool m_bReoriented = false;

    /************************************************************************************/

    Transform m_cTransform;

    /**
    * FUNCTION NAME: OnStart
    * DESCRIPTION  : Stops rotating from starting by default if set.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override protected void OnStart()
    {
        m_cTransform = GetComponent<Transform>();

        if (string.IsNullOrEmpty(m_TargetFacingTag))
        {
            if (m_bPrintDebug)
                LPK_PrintError(this, "No string set as a follow object!");
        }
    }

    /**
    * FUNCTION NAME: FixedUpdate
    * DESCRIPTION  : Manages rotation of objects.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void FixedUpdate()
    {
        if (m_pTargetTransformObject == null)
            FindFacingObject();

        if (m_bOnUpdate || !m_bReoriented)
        {
            if (m_pTargetTransformObject != null && m_pTargetTransformObject.transform != null)
            {
                //Look at desired object.

                Vector3 diff = m_pTargetTransformObject.transform.position - m_cTransform.position;
                diff.Normalize();

                float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
                Quaternion targetRotation = Quaternion.Euler(0f, 0f, rot_z - 90);
                m_cTransform.rotation = Quaternion.RotateTowards(m_cTransform.rotation, targetRotation, Time.deltaTime * m_flRotationSpeed);

                m_bReoriented = true;

                if (m_bPrintDebug)
                    LPK_PrintDebug(this, "Rotation Applied");
            }
            else
            {
                if (m_bPrintDebug)
                    LPK_PrintDebug(this, "Invalid Transform Path");
            }
        }
    }

    /**
    * FUNCTION NAME: FindFacingObject
    * DESCRIPTION  : Sets the ideal object to face.  Will always be the first object with the tag found.  As such
    *                the tag used to find while following should only ever exist once in a scene.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void FindFacingObject()
    {
        if (string.IsNullOrEmpty(m_TargetFacingTag))
            return;

        m_pTargetTransformObject = LPK_MultiTagManager.FindGameObjectWithTag(gameObject, m_TargetFacingTag);

        if(LPK_MultiTagManager.FindGameObjectsWithTag(gameObject, m_TargetFacingTag).Count > 1 && m_bPrintDebug)
            LPK_PrintWarning(this, "WARNNG: Undefined behavior for target facing!  Multiple game objects found with the tag: " + m_TargetFacingTag + 
                             "Please note that in a build, it is undefined which game object will be selected.");
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_RotateTowardsGameObject))]
public class LPK_RotateTowardsGameObjectEditor : Editor
{
    SerializedProperty targetObject;
    SerializedProperty targetFacingTag;

    SerializedProperty eventTriggers;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        targetObject = serializedObject.FindProperty("m_pTargetTransformObject");
        targetFacingTag = serializedObject.FindProperty("m_TargetFacingTag");

        eventTriggers = serializedObject.FindProperty("m_EventTrigger");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_RotateTowardsGameObject owner = (LPK_RotateTowardsGameObject)target;

        LPK_RotateTowardsGameObject editorOwner = owner.GetComponent<LPK_RotateTowardsGameObject>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_RotateTowardsGameObject)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_RotateTowardsGameObject), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_RotateTowardsGameObject");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        owner.m_bOnUpdate = EditorGUILayout.Toggle(new GUIContent("On Update", "Whether to reorient towards mouse every time its position updates. Will only reorient once if set to false."), owner.m_bOnUpdate);
        EditorGUILayout.PropertyField(targetObject, true);
        EditorGUILayout.PropertyField(targetFacingTag, true);
        owner.m_flRotationSpeed = EditorGUILayout.FloatField(new GUIContent("Rotation Speed", "Speed to rotate towards end goal."), owner.m_flRotationSpeed);

        //Events
        EditorGUILayout.PropertyField(eventTriggers, true);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
